package com.quick.framework.exception;

import com.quick.common.core.domain.ApiResponse;
import com.quick.common.exception.ServiceException;
import com.quick.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 全局异常处理器
 *
 * @author 吃素不吃肉
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ApiResponse handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        log.error("请求地址:{},权限校验失败{}", request.getRequestURI(), e.getMessage());
        return ApiResponse.error(HttpStatus.FORBIDDEN.value(), "没有权限");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiResponse handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("请求地址:{},不支持{}请求", request.getRequestURI(), e.getMethod());
        return ApiResponse.error(StringUtils.format("不支持{}请求", e.getMethod()));
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ApiResponse handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("请求地址:{},发生业务异常.{}.", request.getRequestURI(), e.getMessage(),e.getCause());
        Integer code = e.getCode();
        return Objects.isNull(code) ? ApiResponse.error(e.getMessage()) : ApiResponse.error(code, e.getMessage());
    }


    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ApiResponse handleException(Exception e, HttpServletRequest request) {
        log.error("请求地址:{},系统错误.{}", request.getRequestURI(), ExceptionUtils.getStackTrace(e));
        return ApiResponse.error("系统错误");
    }


    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error("请求地址:{},请求参数错误.{}'", request.getRequestURI(), message);
        return ApiResponse.error(StringUtils.format("请求参数错误,{}", message));
    }

}
